// packageRecruit/pages/work-job/work-job.js
import {
    workList,
    workTopInfo,
    jobOffShelf,
    workStatusManage
} from '../../api/recruit'
import dayjs from 'dayjs'

import user from '../../../utils/user'
import { shake, base64ToWxfile, confirm, toast } from '../../../utils/util'
// 二维码分享
import jobCanvas from '../../template/share/share.js'
import { createClientQrCode,getSystemSetUp } from '../../../api/app.js'
const app = getApp()
Page({
    data: {
        workTopInfo: {},
        tabList: [{
            title: '全部',
            num: ''
        },
        {
            title: '招聘中',
            num: ''
        },
        {
            title: '已下架',
            num: ''
        }
        ],
        tabIndex: 0,
        workList: [],
        total: 0,
        hasNextPage: false,
        pageNum: 1,
        pageSize: 20,
        searchText:'',
        shareInfo:{},
        isPoster:false,
        workInfo:{},
        qrcode:'',
        isNeedAuthSalaryCard:''
    },
    onLoad() {
        user.waitLogin().then(() => {
            this.setData({
                pageNum: 1,
                workTopInfo: {},
                workList: []
            })
            this.workJobList(false,true)
            this.getWorkTopInfo()
        })
    },
    onReady() {

    },
     onReachBottom: function() {
        console.log('监听到达底部啦')
      },
    onShow() {
        
    },
    onTab(event) {
        this.setData({
            tabIndex: event.detail,
        })
        this.workJobList(true,true)
    },
    goPending() {
        wx.navigateTo({
            url: '/packageRecruit/pages/pending/pending',
        })
    },
    // 去经营数据
    goWorkData(){
        wx.navigateTo({
            url: '/packageRecruit/pages/work-data/work-data',
        })
    },
    // 重新上架
    onRestart(event){
        const { id } = event.currentTarget.dataset
        wx.navigateTo({
            url: '/packageRecruit/pages/create-basic-info/create-basic-info?type=edit&jobid=' + id,
        })
    },
    
    // 去岗位详情
    goWorkDetail(event){
        const { id } = event.detail.item
        wx.navigateTo({
            url: '/packageRecruit/pages/work-job-detail/work-job-detail?jobid=' + id,
        })
    },
    // 点击三个点回调
    onWaterfallOperation(event){
        this.setData({
            workInfo:event.detail.item
        })
        wx.showActionSheet({
            itemList: ['编辑','删除', this.data.workInfo.jobState ? '下架' : '上架'],
            success:(res)=>{
                const { tapIndex } = res
                if(tapIndex === 2){
                    this.setWorkStatusManage(this.data.workInfo.jobState ? 0 : 1)
                    return
                }
                if(tapIndex === 1){
                    this.onJobOffShelf()
                    return
                }
                if(tapIndex === 0){
                    this.goWorkEdit()
                    return
                }
            }
        })
    },
    // 去编辑
    goWorkEdit(){
        wx.navigateTo({
            url: '/packageRecruit/pages/create-basic-info/create-basic-info?type=edit&jobid=' + this.data.workInfo.id,
        })
    },
    // 上下架
    setWorkStatusManage(){
        confirm(('确定' + (this.data.workInfo.jobState ? '下架' : '上架') + '吗!')).then(res=>{
            workStatusManage({
                id:this.data.workInfo.id,
                jobState:this.data.workInfo.jobState == '1' ? '0' : '1'
            }).then(async ()=>{
                await toast(((this.data.workInfo.jobState ? '下架' : '上架') + '成功'))
                this.workJobList(true,true)
            }) 
        })
    },
    // 岗位删除
    onJobOffShelf(){
        confirm('确定删除吗？').then(res=>{
            jobOffShelf({
                id:this.data.workInfo.id
            }).then(async ()=>{
                await toast('删除成功')
                this.workJobList(true,true)
            }) 
        })
        
    },
    // 点击分享回调
    onShare(event){
        this.setData({
            shareInfo:event.detail.item
        })
        this.handleShareJob()
    },
    // 第二个参数 如果不加第二个参数 则在到达底部时 滚动条会直接跑到顶部 所以 workJobList方法 加入第二个参数
    // wx.lin.renderWaterFlow()支持传入三个参数，第一个参数为data即为传入的数据信息，第二个参数为refresh为是否刷新数据(删除之前渲染的数据，重新渲染)。
    workJobList(empty=false,reRendering) {
        if(empty){
            this.setData({
                workList:[],
                total:0,
                pageNum:1
            })
        }
        workList({
            jobState: this.data.tabIndex == 0 ? '' : this.data.tabIndex == 1 ? 1 : this.data.tabIndex == 2 ? 0 : '',
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize,
            searchText:this.data.searchText
        }).then(res => {
            // new jobCanvas(this, res.list[0])
            if (!res.hasNextPage) {
                this.data.hasNextPage = false
            } else {
                this.data.hasNextPage = true
            }
            res.list.forEach((item, index) => {
                res.list[index].jobDetail = this.handleSpace(item.jobDetail)
				res.list[index].jobTag = item.jobTag.split(';')
				item.showTime = dayjs(item.updateTime).format('YYYY-MM-DD')
                if(res.list[index].jobTag.length === 1 && !res.list[index].jobTag[0]){
                    res.list[index].jobTag = []
				}
				if(item.jobName && item.jobName.startsWith('!') || item.jobName.startsWith('！')) {
					item.isHurry = true
					let reg = /^[!|！]+/
					item.prefix = item.jobName.match(reg)[0] || ''
					item.jobName = item.jobName.replace(/^[!|！]+/, '')
				} else {
					item.isHurry = false
				}
				if (item.jobDetail?.length && item.jobTag?.length) {
					console.log(1234, item);
					let temp = []
					for (let i = 0; i<item.jobDetail.length; i++) {
						if (item.jobTag.every(k => k!==item.jobDetail[i])) {
							temp.push(item.jobDetail[i])
						}
					}
					item.jobDetail = temp
				}
            })
            let arr = []
            arr.push(...this.data.workList)
            arr.push(...res.list)
            this.setData({
                workList: reRendering ? arr : res.list,
                total: res.totalCount
            })
            wx.lin.renderWaterFlow(this.data.workList,reRendering,(res)=>{
            })
            
        })
    },
    getWorkTopInfo() {
        workTopInfo({}).then(res => {
            this.setData({
                workTopInfo: res
            })
        })
    },
    // 滚动到底部
    scrolltolower() {
        if (!this.data.hasNextPage) {
            return
        }
        this.setData({
            pageNum: this.data.pageNum += 1
        })

        this.workJobList(false,false)
    },
    // 海报取消按钮回调
    onCloseShare(){
        this.setData({
            isPoster:false
        })
    },
    // 海报保存按钮回调
    onPreservation(event){
        console.log(event, 'eventevent')
        wx.saveImageToPhotosAlbum({
            filePath: event.detail,
            success(res) {
                app.toast('成功保存')
                console.log(res, 'res')
            },
            fail(rej) {
                app.toast('保存失败')
                console.log(rej)
            }
        })
    },
    // 去创建岗位
    goEstablishWork() {
        wx.navigateTo({
            url: '/packageRecruit/pages/create-basic-info/create-basic-info',
            success: function(res) {
                // 通过 eventChannel 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', { fileList: temporary })
            }
        })
        // wx.chooseMedia({
        //     count:9,
        //     mediaType: ['image',''],
        //     sourceType: ['album'],
        //     maxDuration: 30,
        //     sizeType: ['compressed'],
        //     success:(res)=>{
        //         if (res.tempFiles[0].duration > 30) {
        //             toast('请将视频时长控制在30秒以内')
        //             return
        //         }
        //         if (res.tempFiles[0].fileType === 'video' && res.tempFiles[0].size > 30 * 1024 * 1024) {
        //             toast('请将视频大小控制在30MB以内')
        //             return
        //         }
        //         const temporary = []
        //         temporary.push(...res.tempFiles)
                
        //     }
        // })
    },
    // 去海报分享
    goPosterJob(event) {
        const { id } = event.currentTarget.dataset
        wx.navigateTo({
            url: '/packageRecruit/pages/poster-job/poster-job?id=' + id,
        })
    },
    // 岗位搜索
    searchWorker(event){
        shake(()=>{
            const { value } = event.detail
            this.setData({
                searchText:value,
            })
            this.workJobList(true,true)
        })
    },

    async handleShareJob() {
        this.setData({
            isPoster:true
        })
        const result = await getSystemSetUp({})
        this.setData({
            isNeedAuthSalaryCard: result.isNeedAuthSalaryCard
        })
        // todo 需要传入岗位id获取岗位二维码，当前测试默认22
        const path = await this.createInviteQrCode(this.data.shareInfo.id)
        // 将详情处理成数组
        const workInfo = this.data.workList[this.data.workList.findIndex((item)=>{
            return item.id === this.data.shareInfo.id
        })]
        this.setData({
            workInfo:workInfo,
            qrcode:path
        })
        // workInfo.jobDetail = this.handleSpace(workInfo.jobDetail)
        // new jobCanvas(workInfo, path)
    },

    handleSpace(jobDetail) {
        return jobDetail.replace(/[\r\n]/g,'「').split('「')
    },

    // 岗位分享二维码
    createInviteQrCode(jobId) {
        return new Promise(resolve => {
            // 'id=' + jobId + '&uid=' + user.userId + '&cid=' + user.companyId + '&force=' + (!this.data.isNeedAuthSalaryCard ? 0 : 1)
            let scene =  ''
            scene = 'id=' + jobId + '&uid=' + user.userId  + '&force=' + (!this.data.isNeedAuthSalaryCard ? 0 : 1)
            createClientQrCode({
                page: 'pages/job-detail/job-detail',
                width: 100,
                scene: scene,
            }).then(res => {
                this.setData({
                    ['enterprise.qrId']:res.qrId,
                    qrId:res.qrId
                })
                let qrCode = res // 后台返回的base64图片流
                base64ToWxfile(qrCode, Math.ceil(Math.random() * 10000000000) + '.png').then(path => {
                    // this.setData({
                    //     qrcode: path
                    // })
                    resolve(path)
                })
            })
        })
	},
})